import React, { useEffect, useState } from 'react';
import { Button, Menu, Modal, Form, Input, TreeSelect, Dropdown, message, Popconfirm } from 'antd';
import { MailOutlined, MoreOutlined } from '@ant-design/icons';
import { createSysDept, deleteSysDept, fetchSysDept, updateDeptStatus, queryDeptTree } from '@/services/ant-design-pro/system';

type DepartmentCategoryMenuProps = {
  selectedKey: string;
  onCategorySelect: (key: string) => void;
};

const DepartmentCategoryMenu: React.FC<DepartmentCategoryMenuProps> = ({
  selectedKey,
  onCategorySelect,
}) => {
  const [menuItems, setMenuItems] = useState<Array<{ key: string, label: JSX.Element, children?: any[] }>>([]);
  const [menu, setMenu] = useState<any>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [currentKey, setCurrentKey] = useState<string | null>(null);
  const [currentItem, setCurrentItem] = useState<any>(null);
  const [treeData, setTreeData] = useState<any[]>([]);

  const fetchMenuItems = async () => {
    try {
      const response = await queryDeptTree({});
      const resList = buildMenuItems(response.data);
      setMenu(response.data);
      setMenuItems(resList);
      setTreeData(response.data);
    } catch (error) {
      console.error('Error fetching menu items:', error);
    }
  };

  const buildMenuItems = (data) => {
    return data.map((item) => {
      return {
        key: item.id,
        label: (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ width: '150px', overflow: 'hidden' }}>{item.name}</div>
            <Dropdown
              trigger="click"
              overlay={
                <Menu>
                  <Menu.Item key="edit" onClick={() => handleEdit(item)}>
                    修改
                  </Menu.Item>
                  <Popconfirm
                    title="删除"
                    description="确认删除部门信息么"
                    onConfirm={() => handleDelete(item.id)}
                    okText="是"
                    cancelText="否"
                  >
                    <Menu.Item key="delete">
                      删除
                    </Menu.Item>
                  </Popconfirm>
                </Menu>
              }
            >
              <MoreOutlined />
            </Dropdown>
          </div>
        ),
        children: item.treeList.length ? buildMenuItems(item.treeList) : false,
      };
    });
  };

  useEffect(() => {
    fetchMenuItems();
  }, []);

  const handleSelect = (e) => {
    onCategorySelect(e.key);
    setCurrentKey(e.key);
    const selectedItem = menu.find(item => item.id === e.key);
    setCurrentItem(selectedItem);
  };

  const handleAdd = () => {
    setModalVisible(true);
    setCurrentItem(null);
    form.resetFields();
  };

  const handleOk = () => {
    form.validateFields().then(async values => {
      if (currentItem) {
        // Edit existing department
        await createSysDept({ ...values, id: currentItem.id });
        message.success('编辑成功');
      } else {
        // Add new department
        await createSysDept(values);
        message.success('添加成功');
      }
      fetchMenuItems();
      setModalVisible(false);
      form.resetFields();
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  };

  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields();
  };

  const handleEdit = (item) => {
    setModalVisible(true);
    setCurrentItem(item);
    form.setFieldsValue(item);
  };

  const handleDelete = async (id) => {
    try {
      await deleteSysDept(id);
      message.success('删除成功');
      fetchMenuItems();
    } catch (error) {
      console.error('Error deleting item:', error);
    }
  };

  return (
    <div>
      <Menu
        onSelect={handleSelect}
        style={{ width: 256 }}
        selectedKeys={[currentKey || selectedKey]}
        defaultOpenKeys={['sub1']}
        mode="inline"
        items={[
          {
            key: 'sub1',
            label: (
              <span>
                <MailOutlined />
                <span>部门</span>
              </span>
            ),
            children: [
              ...menuItems,
              {
                key: 'add-button',
                type: 'group',
                label: (
                  <div style={{ textAlign: 'center', marginTop: '16px' }}>
                    <Button type="primary" onClick={handleAdd}>
                      添加
                    </Button>
                  </div>
                ),
              },
            ],
          },
        ]}
      />
      <Modal
        title={currentItem ? "修改部门" : "添加部门"}
        visible={modalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="parentCode" label="选择父级部门">
            <TreeSelect
              treeData={treeData}
              fieldNames={{ label: 'deptName', value: 'code', children: 'treeList' }}
              onSelect={(selectedKeys) => form.setFieldsValue({ parentCode: selectedKeys })}
            />
          </Form.Item>
          <Form.Item name="deptName" label="部门名称" rules={[{ required: true, message: '请输入部门名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="address" label="地址">
            <Input />
          </Form.Item>
          <Form.Item name="deptAllName" label="部门全称">
            <Input />
          </Form.Item>
          <Form.Item name="deptManager" label="部门负责人">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DepartmentCategoryMenu;